import { Toast } from 'vant';
import cTitle from "components/title";

export default {
  data() {
    return {
      endDate:"",
      valid_key:"",
      fullAddress:"",
      showCity: false,
      showCity1: false,
      district: district,
      currentDateKey: "",
      currentCityKey: "",
      pickerShow:false,
      current_key:"",
      info:{},
      pickerValue: new Date(),
      industry:[],
      apply_info:[],
      apply_info_set:'',
      photosize: 1024 * 1024 * 4, // 图片大小限制,
      information: {
        my_name: "",
        phone_number: "",
        store_name: "",
        store_logo: "",
        bank_account: "",
        owner_name: "",
        opening_bank: "",
        opening_branch: "",
        enterprise_alipay: "",
        enterprise_alipay_user: "",
        alipay: "",
        alipay_username: "",
        weChat_account: "",
        category:"",
        group:"",
        imageList:[]
      },
      // setting sun
      imageUrl: "",
      uploadUrl: "",
      jumpState: true,
      fill_set: {},
      // imageList:[]

      license_valid_type:[
        {id: 0,name: "非长期有效"},
        {id: 1,name: "长期有效"},
      ],
      license_type:[
        {id: 1, "name": "个体工商户"},
        {id: 2,"name": "有限责任公司"},
        {id: 3,"name": "其他"}
      ],
      //街道数据
      districtVal: [],
      streetShow: false,
      strShow: false,
      startDate: new Date(1923, 0, 1),
      uploader:[],
      uploader_front:[],
      uploader_back:[],
      uploader_bank_front:[],
      uploader_bank_back:[],
      showLicense:false,
      show_license_valid_type:false,
      apply_info_form:{
        username:"",
        password:"",
        license_img:"",
        license_type:"",
        license_name:"",
        license_code:"",
        license_address_province:"",
        license_address_city:"",
        license_address_district:"",
        license_address_street:"",
        license_address_detail:"",
        license_valid_type:"",
        license_scope:"",
        license_date_start:"",
        license_date_end:"",
        legal_name:"",
        legal_address:"",
        legal_phone:'',
        legal_no:'',
        legal_valid_type:"",
        legal_date_start:"",
        legal_date_end:"",
        legal_img_front:"",
        legal_img_back:"",
        opening_permit:"",
        bank_account_name:"",
        bank_name:"",
        branch_code:"",
        branch_name:"",
        bank_card_no:"",
        owner_name:"",
        bank_sn:"",
        bank_code:"",
        bank_mp:"",
        store_name:"",
        realname:"",
        mobile:"",
        remark:"",
        bank_type:"",
        company_bank:"",
        bank_username:"",
        bank_of_accounts:"",
        opening_branch:"",
        bank_img_front:"",
        bank_img_back:"",
        wechat:"",
        ali_username:"",
        ali:"",
        company_ali_username:"",
        company_ali:"",
      },
      show_bank:false,
      show_category:false,
      bank_info:[
        {title:"银行名称",key:'bank_name'},
        {title:"银行编号",key:'bank_code'},
        {title:"持卡人",key:'owner_name'},
        {title:"银行预留手机号",key:'bank_mp'}
      ],
      bank_info_1:[
        {title:"银行账号",key:'company_bank'},
        {title:"开户人姓名",key:'bank_username'},
        {title:"开户行",key:'bank_of_accounts'},
        {title:"开户支行",key:'opening_branch'},

      ],
      bank_info_2:[
        {title:"银行账户名称",key:'bank_account_name'},
        {title:"银行卡号",key:'bank_card_no'},
        {title:"账户联行号",key:'bank_sn'},
        {title:"支行名称",key:"branch_name"},
        {title:"支行号",key:"branch_code"},
      ],

      choose_date_type:"",
      street_name:"",

      apply_info: [],
    };
  },
  created() {
    this.getFillSet();
  },
  // setting sun
  activated() {
    // console.log("route++params", this.$route.params);
    this.init();
    this.urlUp();
    this.getJson();
  },
  methods: {
    streetChoose() {
      if (this.fun.isTextEmpty(this.fullAddress)) {
        this.$dialog.alert({message:"请先选择所在地区"});
      } else {
        this.streetShow = true;
      }
    },
    setCity1(value) {
      console.log(value,'value===')
      this.apply_info_form.license_address_province=value.itemValue1;
      this.apply_info_form.license_address_city=value.itemValue2;
      this.apply_info_form.license_address_district=value.itemValue3;
      // 重置街区选择
      this.street_name = "";
      this.districtVal = [];
      this.fullAddress = value.itemName1 + " " + value.itemName2 + " " + value.itemName3;
      this.getStreet(value.itemValue3);
    },
    getStreet(param) {
      $http
        .get("member.memberAddress.street", { district_id: param })
        .then(response => {
          if (response.result == 1) {
            if (
              !this.fun.isTextEmpty(response.data) &&
              response.data.length > 0
            ) {
              this.districtVal = response.data;
              this.strShow = true;
            } else {
              this.strShow = false;
            }
          } else {
            this.strShow = false;
          }
        })
        .catch(error => {
          console.log(error);
        });
    },

    streetConfirm(obj) {
      this.street_name = obj.areaname;
      this.apply_info_form.license_address_street = obj.id;
      this.streetShow = false;
    },
    onCancel() {
      this.streetShow = false;
    },
    license_handle(id,key){
      if(key=='valid'){
        if(this.valid_key == 'license_valid_type'){
          this.apply_info_form.license_valid_type = id;
        }else if(this.valid_key=='legal_valid_type'){
          this.apply_info_form.legal_valid_type = id;
        }else{
          this.apply_info_form.bank_type = id;
        }
        console.log(this.apply_info_form.legal_valid_type,'===id==',id,'this.apply_info_form.license_valid_type',this.apply_info_form.license_valid_type)
      }else if(key=='void'){
        this.apply_info_form.bank_type = "";
        this.show_bank = false;
      }else{
        this.apply_info_form.license_type = id;

      }
    },
    upload_license(e,flag){
      this.onReadMore(e, flag,'license_img');
    },
    upload_permit(e,flag){
      this.onReadMore(e, flag,'opening_permit');
    },
    upload_bank_front(e,flag){
      this.onReadMore(e, flag,'bank_img_front');
    },
    upload_bank_black(e,flag){
      this.onReadMore(e, flag,'bank_img_back');
    },
    upload_legal_front(e,flag){
      this.onReadMore(e, flag,'legal_img_front');
    },
    upload_card(e,flag){
      this.onReadMore(e, flag,'legal_img_back');
    },

    setDate(ret) {
      if(this.current_key=='legal_person'){
        if(this.choose_date_type=='start'){
           this.apply_info_form.legal_date_start = ret.Format("yyyy-MM-dd");
        }else{
          this.apply_info_form.legal_date_end = ret.Format("yyyy-MM-dd");
        }
      }else {
        if(this.choose_date_type=='start'){
           this.apply_info_form.license_date_start = ret.Format("yyyy-MM-dd");
        }else{
          this.apply_info_form.license_date_end = ret.Format("yyyy-MM-dd");
        }
      }
      this.pickerShow = false;
    },
     // vant 多图片上传
     onReadMore(e, flag,key) {
      Toast.loading({
        message: "上传中",
        forbidClick: true
      });
      let fd = new FormData();
      if (flag === true) {
        fd.append("file", e);
      } else {
        fd.append("file", e.file); // 第一个参数字符串可以填任意命名，第二个根据对象属性来找到file
      }
      axios
        .post(this.fun.getRealUrl("upload.uploadPic"), fd, {
          headers: { "Content-Type": "multipart/form-data" }
        })
        .then(response => {
          var responseData = response.data;
          if (responseData.result === 1) {
            Toast.clear();
            this.apply_info_form[key] = responseData.data.img_url;
          } else {
            Toast.clear();
            Toast(responseData.msg);
          }
        })
        .catch(error => {
          Toast.clear();
          console.log(error);
        });
    },
    date_handle(type,key){
      this.current_key = key;
      this.choose_date_type = type;
      this.pickerShow = true;
    },
    format_value(item){
      if(item.key=='license_type'){
        return this.info.license_type_name;
      }else if(item.key=='license_valid_type'){
        return this.info.license_valid_type_name;
      }else if(item.key=='license_address'){
        return `${this.info.license_address_city}-${this.info.license_address_district}-${this.info.license_address_province}`
      }else if(item.key=='legal_valid_type'){
        return this.info.legal_valid_type_name;
      }else if(item.key=='legal_date'){
        return `${this.info.legal_date_start_str}-${this.info.legal_date_end_str}`;
      }
      return this.info[item.key]
    },
    getFillSet() {
      $http.post("plugin.supplier.frontend.info.getFillSet").then((response) => {
        if (response.result === 1) {
          this.fill_set = response.data.fill_set;
        }
      }).catch((response) => {
        console.log(response.msg);
      });
    },
    // 初始化信息
    init() {
      var currentDate = new Date();
      currentDate.setFullYear(currentDate.getFullYear() + 50);
      this.endDate = currentDate;

      for (var item in this.information) {
        this.information[item] = "";
      }
      this.imageUrl = "";
    },
    // 获取数据
    getJson() {
      let that = this;
      let json = { member_id: this.$route.params.member_id };
      $http.post("plugin.supplier.frontend.info.index", json).then(
        function(response) {
          console.log('info--res', response);
          if (response.result === 1) {
            that.apply_info_set = response.data.apply_info_set;
            that.apply_info = response.data.apply_info||[];
            that.info = response.data;
            if(response.data.apply_info_set=='1'){
              let form = that.apply_info_form,
                  _data = response.data;
              for (const key in form) {
                  if(key == 'license_img_url'){
                    that.apply_info_form.license_img = _data['license_img_url'];
                  }else if(key=='license_date_end'){
                    that.apply_info_form['license_date_end']=_data['license_date_end_str'];
                  }else if(key=='license_date_start'){
                    that.apply_info_form['license_date_start']=_data['license_date_start_str'];
                  }else if(key=='legal_date_end'){
                    that.apply_info_form['legal_date_end']=_data['legal_date_end_str'];
                  }else if(key=='legal_date_start'){
                    that.apply_info_form['legal_date_start']=_data['legal_date_start_str'];
                  }else if(key=='legal_valid_type' || key=='license_valid_type'){
                    that.apply_info_form[key] = _data[key]
                  }else if(_data[key]){
                    that.apply_info_form[key] = _data[key]
                  }
              }
              if(_data.license_address_province){
                let _arr = district.filter(item=>item.v==_data.license_address_province);
                let _arr1 = _arr[0].c.filter(item=>item.v==_data.license_address_city);
                let _arr2 = _arr1[0].c.filter(item=>item.v==_data.license_address_district);
                that.fullAddress = `${_arr[0].n}-${_arr1[0].n}-${_arr2[0].n}`;
              }


            }

            that.information.my_name = response.data.realname;
            that.information.phone_number = response.data.mobile;
            that.information.store_name = response.data.store_name;
            that.information.store_logo = response.data.logo;
            that.imageUrl = response.data.logo;
            that.information.bank_account = response.data.company_bank;
            that.information.owner_name = response.data.bank_username;
            that.information.opening_bank = response.data.bank_of_accounts;
            that.information.opening_branch = response.data.opening_branch;
            that.information.enterprise_alipay = response.data.company_ali;
            that.information.enterprise_alipay_user = response.data.company_ali_username;
            that.information.alipay = response.data.ali;
            that.information.alipay_username = response.data.ali_username;
            that.information.weChat_account = response.data.wechat;
            that.information.category =  response.data.has_one_category ? response.data.has_one_category.title : '默认行业';
            that.information.group =  response.data.has_one_group ? response.data.has_one_group.title : '默认分组';
            that.information.imageList =  response.data.has_one_aptitude?.aptitude || [];
          } else {
            // 判断权限
            if (response.data.url) {
              that.$notify(response.msg);
              window.location.href = response.data.url;
              return 0;
            }
            // that.$message.error(response.msg)
            that.$notify(response.msg);
          }
        },
        function(response) {
          console.log(response);
        }
      );
    },
    // 确认修改
    modifyInformation() {
      var that = this;
      that.jumpJudge();
      if (that.jumpState == true) {
        if (that.fun.isMoblie(that.information.phone_number)) {
          this.$notify("请输入正确的手机号");
          // this.$message.error('请输入正确的手机号')
          return;
        }
        if (this.fill_set.company_bank == "1") {
          if ( !/^[0-9]*$/.test(that.information.bank_account) ) {
            this.$notify("请输入正确的银行卡账号");
            return;
          }
        }

        if (this.fill_set.company_ali == "1") {
          if (
            !/^(?:\w+\.?)*\w+@(?:\w+\.)+\w+|\d{9,11}$/.test(
              that.information.enterprise_alipay
            )
          ) {
            this.$notify("请输入正确的企业支付宝账号");
            return;
          }
        }

        if (this.fill_set.ali == "1") {
          if (
            !/^(?:\w+\.?)*\w+@(?:\w+\.)+\w+|\d{9,11}$/.test(
              that.information.alipay
            )
          ) {
            this.$notify("请输入正确的支付宝账号");
            return;
          }
        }

        if (this.fill_set.wechat == "1") {
          if (
            !/^[a-zA-Z]([-_a-zA-Z0-9]{5,19})+$/.test(
              that.information.weChat_account
            )
          ) {
            this.$notify("请输入正确的微信号");
            return;
          }
        }

        let json = {
          realname: that.information.my_name,
          mobile: that.information.phone_number,
          store_name: that.information.store_name,
          logo: that.information.store_logo,
          company_bank: that.information.bank_account,
          bank_username: that.information.owner_name,
          bank_of_accounts: that.information.opening_bank,
          opening_branch: that.information.opening_branch,
          company_ali: that.information.enterprise_alipay,
          company_ali_username: that.information.enterprise_alipay_user,
          ali: that.information.alipay,
          ali_username: that.information.alipay_username,
          wechat: that.information.weChat_account
        };
        $http.post("plugin.supplier.frontend.info.edit", json).then(
          function(response) {
            console.log("midify", response);
            if (response.result === 1) {
              that.$router.push(
                that.fun.getUrl("SupplierCenter", {
                  uid: that.$route.params.member_id
                })
              );
              that.$notify({
                background: "#f0f9eb",
                message: "修改成功",
                color: "#67c23a"
              });
            } else {
              that.$notify(response.msg);
              // that.$message.error(response.msg)
            }
          },
          function(response) {
            console.log(response);
          }
        );
      } else {
        that.$notify({
          background: "#fef0f0",
          message: "填写信息不完整",
          color: "#f56c6c"
        });
      }
    },
    // 确认条件
    jumpJudge() {
      this.jumpState = true;

      if (!this.information.my_name || !this.information.phone_number || !this.information.store_name || !this.information.store_logo) {
        this.jumpState = false;
      }

      // for (var item in this.information) {
      //   if (this.information[item] == "") {
      //     this.jumpState = false;
      //   }
      // }
      if (this.fill_set) {
        if (this.fill_set.company_bank == "1") {
          if (this.information.bank_account == "") {
            this.jumpState = false;
          }
        }
        if (this.fill_set.bank_username == "1") {
          if (this.information.owner_name == "") {
            this.jumpState = false;
          }
        }
        if (this.fill_set.bank_of_accounts == "1") {
          if (this.information.opening_bank == "") {
            this.jumpState = false;
          }
        }
        if (this.fill_set.opening_branch == "1") {
          if (this.information.opening_branch == "") {
            this.jumpState = false;
          }
        }
        if (this.fill_set.company_ali == "1") {
          if (this.information.enterprise_alipay == "") {
            this.jumpState = false;
          }
        }
        if (this.fill_set.company_ali_username == "1") {
          if (this.information.enterprise_alipay_user == "") {
            this.jumpState = false;
          }
        }
        if (this.fill_set.ali == "1") {
          if (this.information.alipay == "") {
            this.jumpState = false;
          }
        }
        if (this.fill_set.ali_username == "1") {
          if (this.information.alipay_username == "") {
            this.jumpState = false;
          }
        }
        if (this.fill_set.wechat == "1") {
          if (this.information.weChat_account == "") {
            this.jumpState = false;
          }
        }
      }

      if (this.imageUrl == "") {
        this.jumpState = false;
      }
    },
    // setting sun
    // 上传url
    urlUp() {
      this.uploadUrl = this.fun.getRealUrl(
        "upload.uploadPic",
        {}
      );
    },
    // 上传成功
    handleStoreSuccess(res, file) {
      console.log(res);
      this.imageUrl = URL.createObjectURL(file.raw);
      if (res.result == 1) {
        this.information.store_logo = res.data.img;
      } else {
        Toast(res.msg);
      }
    },
    // 上传前
    beforeUpload(file) {
      // const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === "image/png" || file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isPNG) {
        // this.$message.error('上传头像图片只能是 JPG或PNG 格式!')
        this.$notify("上传头像图片只能是 JPG或PNG 格式!");
      }
      if (!isLt2M) {
        // this.$message.error('上传头像图片大小不能超过 2MB!')
        this.$notify("上传头像图片大小不能超过 2MB!");
      }
      return isPNG && isLt2M;
    },
    /*vant图片上传*/
    onRead(e) {
      let fd = new FormData();
      fd.append("file", e.file); // 第一个参数字符串可以填任意命名，第二个根据对象属性来找到file
      var That = this;
      axios
        .post(this.uploadUrl, fd, {
          headers: { "Content-Type": "multipart/form-data" }
        })
        .then(response => {
          var responseData = response.data;
          if (responseData.result == 1) {
            That.imageUrl = URL.createObjectURL(e.file);
            That.information.store_logo = responseData.data.img;
          } else {
            Toast(responseData.msg);
          }
          // this.img.push(res.data.imgpath)
        })
        .catch(error => {
          console.log(error);
        });
    },
    onphotosize(e) {
      this.$notify("上传图片大小不能超过 2MB!");
      // this.$message.error('上传图片大小不能超过 2MB!')
    },

    show_select_value(item){
      let res = this.apply_info_form[item.key];
      if(item.key=='license_type'){
        return res ==1?'个体户':res==2?'有限责任公司':res==3?'其他':'请选择商户类型';
      }else if(item.key=='license_valid_type'){
        return res ===  0 ? '非长期有效' : res == 1 ?'长期有效':'请选择';
      }else if(item.key=='legal_valid_type'){
        console.log(item,'item===',this.apply_info_form);
        return res ===  0 ? '非长期有效' : res == 1 ?'长期有效':'请选择';
      }else if(item.key=='bank_info'){
        return this.apply_info_form.bank_type==1?'对私':this.apply_info_form.bank_type==2?'对公':'';
      } else{
        return this.fullAddress||'请选择'
      }

    },
    form_handle(){
      let form = {...this.apply_info_form}
      let _json = {};
          for (const key in form) {
            if (form[key]||form[key]===0) {
              _json[key]=form[key];
            }
          }
      if(_json.license_date_end){
        let date = _json.license_date_end.replace(/\-/g,'/');
        _json.license_date_end = Math.floor(new Date(date).getTime() / 1000)
      }
      if(_json.license_date_start){
        let date = _json.license_date_start.replace(/\-/g,'/');
        _json.license_date_start = Math.floor(new Date(date).getTime() / 1000)
      }
      if(_json.legal_date_end){
        let date = _json.legal_date_end.replace(/\-/g,'/');
        _json.legal_date_end = Math.floor(new Date(date).getTime() / 1000)
      }
      if(_json.legal_date_start){
        let date = _json.legal_date_start.replace(/\-/g,'/');
        _json.legal_date_start = Math.floor(new Date(date).getTime() / 1000)
      }

      if(this.apply_info_form.license_valid_type==1){
        _json.license_date_end&&delete _json.license_date_end;
      }
      if(this.apply_info_form.legal_valid_type==1){
        _json.legal_date_end&&delete _json.legal_date_end;

      }

      $http.post("plugin.supplier.frontend.info.edit", _json).then(
        response=> {
          if (response.result === 1) {
            this.$router.push(
              this.fun.getUrl("SupplierCenter", {
                uid: this.$route.params.member_id
              })
            );
            this.$notify({
              background: "#f0f9eb",
              message: "修改成功",
              color: "#67c23a"
            });
          } else {
            this.$notify(response.msg);
          }
        },
        function(response) {
          console.log(response);
        }
      );
    },
    popup_handle(key){
      if(key=='license_type'){
        this.showLicense = true;
      }else if(key=='license_valid_type'||key=='legal_valid_type'){
        this.valid_key = key;
        this.show_license_valid_type = true;
      }else if(key=='license_address'){
        this.showCity1 = true;
      }else if(key=='stree'){
        this.streetShow =  true;
      }else if(key=='bank_info'&&this.info.bank_info_edit==0){
        this.show_bank = true;
      }
    },
  },
  watch: {
    "apply_info_form.bank_type"(newV){
        let bank_info = [
          {title:"银行名称",key:'bank_name'},
          {title:"银行编号",key:'bank_code'},
          {title:"持卡人",key:'owner_name'},
          {title:"银行预留手机号",key:'bank_mp'}
        ]
        if(newV==1){
          this.bank_info = bank_info.concat(this.bank_info_1);
        }else if(newV==2){
          this.bank_info = bank_info.concat(this.bank_info_2);
        }else{
          this.bank_info = bank_info;
        }
    }
  },
  components: { cTitle }
};
